import router from "@/router";
import store from "@/store";
import { getToken } from "@/utils/common";
import axios from "axios";
import { MessageBox, Notification } from "element-ui";
import { $session, $store } from "@/utils/store";
let flag = false;
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";
// 创建axios实例
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 600000,
  validateStatus: (status) => {
    // 错误编码为2开头和400报错误提示
    return (status >= 200 && status < 300) || status == 400;
  },
});

// request拦截器
request.interceptors.request.use(
  (config) => {
    if (getToken()) {
      config.headers["Authorization"] = "Bearer " + getToken();
      config.headers["Cur-Industry-Code"] =
        store.state.user.userInfo.industryCode;
    }
    config.headers["x-frame-options"] = "SAMEORIGIN";

    // 处理window 版本
    try {
      let windowsVersion = "";
      let tempNav = navigator.userAgentData;
      tempNav.getHighEntropyValues(["platformVersion"]).then((ua) => {
        if (tempNav.platform === "Windows") {
          const majorPlatformVersion = parseInt(
            ua.platformVersion.split(".")[0]
          );
          if (majorPlatformVersion >= 13) {
            windowsVersion = "Windows 11";
            config.headers["windows_os"] = windowsVersion;
          }
        }
      });
    } catch (err) {
      console.log(err);
    }
    return config;
  },

  (error) => {
    Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const msg = res.data.msg || res.data.message; // 网关响应参数可能为msg或message
    if (
      res.data.code === 200 ||
      res.data.code === 204 ||
      res.data.code === 2001 ||
      res.data.code === 4000 ||
      String(res.data.code).substring(0, 3) === "300"
    ) {
      return res.data;
    } else if (
      (res.data.code === 400 ||
        res.data.code === 4001 ||
        res.data.code === 4000) &&
      res.data.msg
    ) {
      return res.data;
    } else if (res.data.code === 500) {
      return res.data;
    } else if (res.data.code === 401) {
      // 401:token失效
      sessionStorage.clear();
      $store.clear();
      $session.clear();
      MessageBox.alert(msg + "，请重新联系管理员或重新登录", "系统提示", {
        confirmButtonText: "确定",
        type: "warning",
        callback: (action) => {
          try {
            store.dispatch("FedLogOut").then(
              () => {
                // 为了重新实例化vue-router对象 避免bug
                location.reload();
                router.push({
                  path: "/login",
                });
              },
              (err) => {
                router.push({
                  path: "/login",
                });
              }
            );
          } catch {
            router.push({
              path: "/login",
            });
          }
          location.reload();
        },
      });
    } else {
      if (msg === "未知异常，请联系管理员") {
        Notification.error({
          title: "错误",
          message: msg,
        });
      }
      return Promise.reject(res);
    }
  },
  (error) => {
    let { message } = error;
    let timer;
    if (message === "Network Error") {
      message = "系统接口请求异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      const code = message.substr(message.length - 3);
      if (code === "503") {
        Notification.warning({
          title: "警告",
          message: "服务尚未注册成功,请确认已启动服务后稍等!",
        });
      } else if (code === "401") {
        sessionStorage.clear();
        $store.clear();
        $session.clear();
        // 401:token失效
        if (!flag) {
          flag = true;
          MessageBox.alert(
            "暂未登录或token已经过期，请重新联系管理员或重新登录",
            "系统提示",
            {
              confirmButtonText: "确定",
              type: "warning",
              callback: (action) => {
                store
                  .dispatch("FedLogOut")
                  .then(
                    () => {
                      flag = false;
                      router.push({
                        path: "/login",
                      });
                    },
                    (err) => {
                      router.push({
                        path: "/login",
                      });
                    }
                  )
                  .catch(() => {
                    router.push({
                      path: "/login",
                    });
                  });
                location.reload();
              },
            }
          );
        }
      } else {
        let msg =
          error?.response?.data?.msg ||
          error?.response?.data?.message ||
          "系统接口" + message.substr(message.length - 3) + "异常";
        Notification.error({
          title: "错误",
          message: msg,
        });
      }
    } else {
      message = "系统接口请求异常";
    }
    return Promise.reject(error);
  }
);

export default request;

// 转换Promise返回结构
export const TR = async (promise) => {
  try {
    const res = await promise;
    return [null, res];
  } catch (e) {
    console.error(e);
    return [e, null];
  }
};
